package router

import (
	"crow-qin/app/pkg"
	"crow-qin/app/service"
	"errors"
	"github.com/gin-gonic/gin"
)

// Login 用户登录
// @Summary 用户登录
// @Description 用户登录，并获取token
// @Tags system
// @Accept  application/json
// @Product application/json
// @Param data body LoginRequest  true "用户名，用户密码"
// @Success 200 {object} response.Response{data=string} "{"requestId": "string","code": 200,"msg": "ok","data": [...]}"
// @Failure 500 {object} response.Response{msg=string} "{"requestId": "string","code": 500,"msg": "string","status": "error","data": null}"
// @Router /api/v1/login [post]
func (u *rUser) Login(c *gin.Context) {
	u = &rUser{}
	var request LoginRequest
	err := c.Bind(&request)
	if err != nil {
		SetErrDefault(c, err)
		return
	}
	//根据用户名获取用户信息
	u.UserName = request.UserName
	err = u.GetUserByUserName()
	if err != nil {
		SetErrDefault(c, err)
		return
	}
	//检查密码
	if u.Password != pkg.EncryptWithMd5(request.Password) {
		err = errors.New("密码验证错误")
		SetErrDefault(c, err)
		return
	}

	var jc service.JWTClaims
	jc.Set(u.ID, u.UserName, request.Password, u.UserName)
	crowToken, err := jc.CreateToken()
	if err != nil {
		SetErrDefault(c, err)
		return
	}
	SetOK(c, crowToken)
}

// LoginRequest
// 登录需要传入的参数
type LoginRequest struct {
	UserName string `json:"user_name"`
	Password string `json:"password"`
}

// Refresh 刷新token
// @Summary 刷新token
// @Description 刷新用户token
// @Tags system
// @Accept  application/json
// @Product application/json
// @Success 200 {object} response.Response{data=string} "{"requestId": "string","code": 200,"msg": "ok","data": [...]}"
// @Failure 500 {object} response.Response{msg=string} "{"requestId": "string","code": 500,"msg": "string","status": "error","data": null}"
// @Router /api/v1/login/refresh [post]
// @Security Bearer
func (u *rUser) Refresh(c *gin.Context) {
	u = &rUser{}
	strToken, err := pkg.GetTokenFromC(c)
	if err != nil {
		SetErrDefault(c, err)
		return
	}

	j := service.JWTClaims{}
	newToken, err := j.RefreshToken(strToken)
	if err != nil {
		SetErrDefault(c, err)
		return
	}
	SetOK(c, newToken)
}

// Logout 用户登出
// @Summary 用户登出
// @Description 用户登出
// @Tags system
// @Accept  application/json
// @Product application/json
// @Success 200 {object} response.Response{data=string} "{"requestId": "string","code": 200,"msg": "ok","data": [...]}"
// @Failure 500 {object} response.Response{msg=string} "{"requestId": "string","code": 500,"msg": "string","status": "error","data": null}"
// @Router /api/v1/logout [post]
// @Security Bearer
func (u *rUser) Logout(c *gin.Context) {

	//从header中获取token
	strToken, err := pkg.GetTokenFromC(c)
	if err != nil {
		SetErrDefault(c, err)
		return
	}
	//删除redis中的token
	err = service.Logout(strToken)
	if err != nil {
		SetErrDefault(c, err)
		return
	}
	SetOK(c, "登出成功")
}
